<template>
    <div class="flex-col">
        <div class="flex-row justify-center" style="margin-bottom: 10px">
            <template v-for="(value, type) in paperTypes">
                <button :class="curPaperType() === type ? 'api' : 'info'" @click="setPaper(type, value)">
                    {{ type }}
                </button>
            </template>
            <button :class="'other' == curPaperType() ? 'api' : 'info'" class="auto" @click="showPaperPop">自定义纸张</button>
            <div class="popover">
                <div class="popover-content flex-col" v-show="paperPopVisible">
                    <div style="font-size: 16px; font-weight: bold">设置纸张宽高(mm)</div>
                    <div class="flex-row mt-10">
                        <input class="input" v-model="paperWidth" @input="limitWidthTwoDecimals" type="number" placeholder="宽(mm)" />
                        <span class="ml-10 mr-10">x</span>
                        <input class="input" v-model="paperHeight" @input="limitHeightTwoDecimals" type="number" placeholder="高(mm)" />
                    </div>
                    <template>
                        <button class="primary circle-10" style="margin-top: 6px" @click.stop="setPaperOther">确定</button>
                        <button class="primary circle-10" style="margin-top: 6px" @click="paperPopVisible = false">取消</button>
                    </template>
                </div>
            </div>
            <div class="flex-row align-center ml-10">
                <button class="info circle-10" @click="changeScale(false)"><i class="iconfont sv-zoom-out" /></button>
                <div style="margin: 0 4px; width: 40px">{{ (state.scaleValue * 100).toFixed(0) }}%</div>
                <button class="info circle-10" @click="changeScale(true)"><i class="iconfont sv-zoom-in" /></button>
            </div>
            <button class="api circle-10 circle-10 ml-10" @click.stop="exportJson">
                <i class="iconfont sv-export" />
                保存
            </button>
            <button class="secondary circle-10 ml-10" @click.stop="print">
                <i class="iconfont sv-printer" />
                浏览器打印
            </button>
            <button class="warning circle-10 ml-10" @click.stop="print2">
                直接打印(需要连接客户端)
                <i class="iconfont sv-printer" />
            </button>
        </div>
        <div class="flex-row" style="height: 87vh">
            <div class="flex-2 left flex-col">
                <div class="title">默认组件</div>
                <div id="provider-container1" class="container rect-printElement-types"></div>
                <div class=""></div>
            </div>
            <div class="flex-5 center">
                <!-- 设计器的 容器 -->
                <div id="hiprint-printTemplate"></div>
            </div>
            <div class="flex-2 right">
                <!-- 元素参数的 容器 -->
                <div id="PrintElementOptionSetting"></div>
            </div>
        </div>
    </div>
</template>

<script>
import { hiprint } from "vue-plugin-hiprint";
import "@/untils/style.css";
import { provider1 } from "@/untils/provider1";
import { SavePrintTempForHiprint } from "@/service/baseapi";
export default {
    data() {
        return {
            template: "",
            data: "",
            paperWidth: null,
            paperHeight: null,
            paperPopVisible: false,
            hiprintTemplate: null,
            state: {
                scaleValue: 1,
                scaleMax: 5,
                scaleMin: 0.5
            },
            curPaper: {
                type: "A4",
                width: 210,
                height: 296.6
            },
            paperTypes: {
                A3: {
                    width: 420,
                    height: 296.6
                },
                A4: {
                    width: 210,
                    height: 296.6
                },
                A5: {
                    width: 210,
                    height: 147.6
                },
                B3: {
                    width: 500,
                    height: 352.6
                },
                B4: {
                    width: 250,
                    height: 352.6
                },
                B5: {
                    width: 250,
                    height: 175.6
                }
            }
        };
    },
    created() {
        this.data = this.$route.params.zqh;
        this.template = JSON.parse(this.data.template);
        if (this.data.paperWidth) {
            this.paperWidth = this.data.paperWidth;
            this.paperHeight = this.data.paperHeight;
            this.curPaper.width = this.data.paperWidth;
            this.curPaper.type = this.data.paperType;
            this.curPaper.height = this.data.paperHeight;
        }
    },
    mounted() {
        hiprint.init({
            providers: [provider1()]
        });
        this.buildLeftElement();
        this.buildDesigner();
    },
    methods: {
        limitWidthTwoDecimals(event) {
            // 获取输入框的当前值
            let value = event.target.value;
            // 使用正则表达式限制只能输入两位小数
            this.paperWidth = this.checkNumberTwoDecimals(value);
        },
        limitHeightTwoDecimals(event) {
            let value = event.target.value;
            // 使用正则表达式限制只能输入两位小数
            this.paperHeight = this.checkNumberTwoDecimals(value);
        },
        checkNumberTwoDecimals(value) {
            const regex = /^(0|([1-9][0-9]*))(\.[\d]{1,2})$/;
            // 如果值不匹配正则表达式，则将其设置为匹配的部分
            if (!regex.test(value)) {
                value = value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
                value = value.replace(/^\./g, ""); //验证第一个字符是数字而不是字符
                value = value.replace(/\.{2,}/g, "."); //只保留第一个.清除多余的
                value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
                value = value.replace(/^(-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
            }
            return value;
        },
        setPaperOther() {
            let value = {};
            value.width = this.paperWidth;
            value.height = this.paperHeight;
            this.paperPopVisible = false;
            this.setPaper("other", value);
        },
        showPaperPop() {
            this.paperPopVisible = true;
        },
        //更换纸张
        setPaper(type, value) {
            try {
                if (Object.keys(this.paperTypes).includes(type)) {
                    this.curPaper = { type: type, width: value.width, height: value.height };
                    this.hiprintTemplate.setPaper(value.width, value.height);
                } else {
                    this.curPaper = { type: "other", width: value.width, height: value.height };
                    this.hiprintTemplate.setPaper(value.width, value.height);
                }
            } catch (error) {
                alert(`操作失败: ${error}`);
            }
        },
        //绑定初始纸张
        curPaperType() {
            let type = "other";
            let types = this.paperTypes;
            for (const key in types) {
                let item = types[key];
                let { width, height } = this.curPaper;
                if (item.width === width && item.height === height) {
                    type = key;
                }
            }
            return type;
        },
        //放大缩小器
        changeScale(big) {
            let scaleValue = this.state.scaleValue;
            if (big) {
                scaleValue += 0.1;
                if (scaleValue > this.state.scaleMax) scaleValue = 5;
            } else {
                scaleValue -= 0.1;
                if (scaleValue < this.state.scaleMin) scaleValue = 0.5;
            }
            this.hiprintTemplate.zoom(scaleValue);
            this.state.scaleValue = scaleValue;
        },
        buildLeftElement() {
            $("#provider-container1").empty(); // 先清空, 避免重复构建
            hiprint.PrintElementTypeManager.build(
                // eslint-disable-next-line no-undef
                $("#provider-container1"),
                "providerModule1"
            );
        },
        buildDesigner() {
            console.log(this.template);
            // eslint-disable-next-line no-undef
            $("#hiprint-printTemplate").empty(); // 先清空, 避免重复构建
            this.hiprintTemplate = new hiprint.PrintTemplate({
                template: this.template,
                settingContainer: "#PrintElementOptionSetting" // 元素参数容器
            });
            // 构建 并填充到 容器中
            // 可以先 console.log($("#hiprint-printTemplate")) 看看是否有该 dom
            this.hiprintTemplate.design("#hiprint-printTemplate");
        },
        print() {
            // 打印数据，key 对应 元素的 字段名
            let printData = {};
            // 参数: 打印时设置 左偏移量，上偏移量
            let options = { leftOffset: -1, topOffset: -1 };

            // 调用浏览器打印
            this.hiprintTemplate.print(printData, options, ext);
        },
        print2() {
            if (hiprint.hiwebSocket.opened) {
                this.hiprintTemplate.print2();
            } else {
                alert("请先连接客户端(刷新网页), 然后再点击「直接打印」");
            }
        },
        exportJson() {
            let printData = {};
            //let json = this.hiprintTemplate.getHtml(printData);
            let json = this.hiprintTemplate.getJson();
            var that = this;
            if (!this.data) {
                this.$message.error("页面已重置，请回打印模板页面重新选择设计");
                return;
            }
            this.data.template = JSON.stringify(json);
            this.data.paperHeight = this.curPaper.height;
            this.data.paperWidth = this.curPaper.width;
            this.data.paperType = this.curPaper.type;
            SavePrintTempForHiprint(this.data)
                .then(res => {
                    that.$router.back();
                    that.$message({ message: "操作成功", type: "success" });
                })
                .catch(err => {
                    that.$message.error("操作失败");
                });
        }
    }
};
</script>

<style>
/* 重写全局 hiprint 样式 */
.hiprint-headerLine,
.hiprint-footerLine {
    border-color: purple !important;
}

.hiprint-headerLine:hover,
.hiprint-footerLine:hover {
    border-top: 3px dashed purple !important;
}

.hiprint-headerLine:hover:before {
    content: "页眉线";
    left: calc(50% - 18px);
    position: relative;
    background: #ffff;
    top: -14px;
    color: purple;
    font-size: 12px;
}

.hiprint-footerLine:hover:before {
    content: "页脚线";
    left: calc(50% - 18px);
    position: relative;
    color: purple;
    background: #ffff;
    top: -14px;
    font-size: 12px;
}
</style>
<style scoped>
/* api按钮 */
.api {
    background: #00acc1;
}
.left .container {
    height: 100%;
    overflow: auto;
    padding: 0 10%;
    background: rgb(236 216 235);
}
.auto {
    width: auto !important;
}
/* 纸张 */
.paper {
    margin-right: 10px;
}
.paper button:not(class*="auto") {
    width: 60px !important;
}
/* 多个 button 间距 */
.paper button + button {
    margin-left: -1px;
}
.paper button:first-child:last-child {
    border-radius: 4px;
}
/* 两边的 btn 圆角 */
.paper button:first-child:not(:last-child) {
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
}
.paper button:last-child:not(:first-child) {
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
}
.popover {
    position: absolute;
    margin-top: 10px;
    z-index: 10;
}
.popover .popover-content {
    background: white;
    border-radius: 4px;
    padding: 10px 14px;
    box-shadow: 2px 2px 2px 4px rgb(128 0 128 / 20%);
}
.popover .input {
    height: 24px;
    padding: 2px 4px;
}
.popover .input:hover {
    border-color: rgb(245, 155, 241);
    border-radius: 4px;
}

/* 区域 */
.left {
    background: white;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    padding: 10px 0;
    box-shadow: 2px 2px 2px 0px rgb(128 0 128 / 20%);
    overflow: auto;
}
.center {
    margin: 0 10px;
    background: white;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    padding: 20px;
    box-shadow: 2px 2px 2px 0px rgb(128 0 128 / 20%);
    overflow: auto;
}
.right {
    background: white;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    padding: 10px 0;
    box-shadow: 2px 2px 2px 0px rgb(128 0 128 / 20%);
    overflow: auto;
}
/* 左侧拖拽元素样式 */
.title {
    font-size: 16px;
    font-weight: 500;
    width: 100%;
    margin: 10px 0 0 24px;
}
.item {
    display: flex;
    flex-direction: column;
    align-items: center;
    background: white;
    padding: 4px 10px;
    margin: 10px 8px 4px 8px;
    width: 38%;
    min-height: 60px;
    border-radius: 4px;
    box-shadow: 2px 2px 2px 2px rgba(171, 171, 171, 0.2);
}
.item .iconfont {
    font-size: 1.5rem;
}
.item span {
    font-size: 14px;
}
</style>
